<template>
  <el-dialog
    :model-value="props.modelValue"
    @update:model-value="emit('update:modelValue', $event)"
    :title="isEdit ? '编辑加白规则' : '添加加白规则'"
    width="700px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="formRules"
      label-width="100px"
      class="rule-form"
    >
      <!-- 基本信息 -->
      <el-form-item label="*规则名称" prop="name">
        <el-input
          v-model="ruleForm.name"
          placeholder="如: 办公网IP段"
          maxlength="50"
        />
        <div class="form-hint">必填, 用于识别规则</div>
      </el-form-item>

      <el-form-item label="*规则类型" prop="type">
        <el-select
          v-model="ruleForm.type"
          placeholder="请选择规则类型"
          @change="handleTypeChange"
        >
          <el-option label="IP地址" value="ip" />
          <el-option label="IP段" value="ip_range" />
          <el-option label="端口" value="port" />
          <el-option label="IP+端口" value="ip_port" />
          <el-option label="场景" value="scene" />
          <el-option label="漏洞" value="vuln_type" />
        </el-select>
      </el-form-item>

      <el-form-item label="规则描述" prop="description">
        <el-input
          v-model="ruleForm.description"
          type="textarea"
          rows="2"
          placeholder="说明规则用途"
          maxlength="200"
        />
        <div class="form-hint">选填, 说明规则用途</div>
      </el-form-item>

      <!-- 匹配条件 (动态显示) -->
      <el-form-item label="*匹配条件" class="condition-group">
        <template v-if="ruleForm.type === 'ip'">
          <el-input
            v-model="ruleForm.condition.ip"
            placeholder="如: 192.168.1.100"
            class="condition-input"
          />
          <div class="form-hint">IP地址格式校验</div>
        </template>

        <template v-if="ruleForm.type === 'ip_range'">
          <el-input
            v-model="ruleForm.condition.ipRange"
            placeholder="如: 192.168.1.0/24 或 192.168.1.1-100"
            class="condition-input"
          />
          <div class="form-hint">支持CIDR格式或IP范围</div>
        </template>

        <template v-if="ruleForm.type === 'port'">
          <el-input
            v-model="ruleForm.condition.port"
            placeholder="如: 80, 443, 8080-8090"
            class="condition-input"
          />
          <div class="form-hint">端口范围1-65535</div>
        </template>

        <template v-if="ruleForm.type === 'ip_port'">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-input
                v-model="ruleForm.condition.ip"
                placeholder="IP地址"
                class="condition-input"
              />
            </el-col>
            <el-col :span="12">
              <el-input
                v-model="ruleForm.condition.port"
                placeholder="端口"
                class="condition-input"
              />
            </el-col>
          </el-row>
        </template>

        <template v-if="ruleForm.type === 'scene'">
          <el-select
            v-model="ruleForm.condition.scene"
            placeholder="请选择场景类型"
          >
            <el-option label="未报备资产" value="unreported" />
            <el-option label="高危资产" value="high_risk" />
            <el-option label="漏洞扫描" value="vuln_scan" />
            <el-option label="情报命中" value="intel_hit" />
            <el-option label="复核确认" value="reviewed" />
          </el-select>
        </template>

        <template v-if="ruleForm.type === 'vuln_type'">
          <el-input
            v-model="ruleForm.condition.vulnKeyword"
            placeholder="如: SQL注入"
            class="condition-input"
          />
          <el-radio-group
            v-model="ruleForm.condition.matchType"
            class="radio-group"
          >
            <el-radio label="exact">完全匹配</el-radio>
            <el-radio label="include">包含</el-radio>
          </el-radio-group>
        </template>
      </el-form-item>

      <!-- 适用场景 -->
      <el-form-item label="适用场景">
        <el-checkbox-group v-model="ruleForm.applicableScenes">
          <el-checkbox label="unreported">未报备资产告警</el-checkbox>
          <el-checkbox label="high_risk">高危资产告警</el-checkbox>
          <el-checkbox label="vuln_scan">漏洞扫描告警</el-checkbox>
          <el-checkbox label="intel_hit">威胁情报告警</el-checkbox>
          <el-checkbox label="reviewed">漏洞复核告警</el-checkbox>
          <el-checkbox label="all" @change="handleAllSceneChange">
            全部场景 (选中后上方全选)
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <!-- 生效时间 -->
      <el-form-item>
        <el-checkbox v-model="ruleForm.hasExpireTime" class="expire-checkbox">
          设置生效时间范围
        </el-checkbox>
        <el-row :gutter="10" v-if="ruleForm.hasExpireTime">
          <el-col :span="12">
            <el-date-picker
              v-model="ruleForm.startTime"
              type="datetime"
              placeholder="开始时间"
              class="time-picker"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-col>
          <el-col :span="12">
            <el-date-picker
              v-model="ruleForm.endTime"
              type="datetime"
              placeholder="结束时间"
              class="time-picker"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-col>
        </el-row>
        <div class="form-hint">不勾选表示永久生效</div>
      </el-form-item>

      <!-- 其他设置 -->
      <el-form-item label="状态设置">
        <el-radio-group v-model="ruleForm.status">
          <el-radio label="启用中">立即启用</el-radio>
          <el-radio label="已禁用">创建后禁用(需要手动启用)</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, defineProps, defineEmits, onMounted } from "vue";
import { ElMessage } from "element-plus";
import type { ElForm } from "element-plus";

// 定义props
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  rule: {
    type: Object,
    default: () => ({}),
  },
  isEdit: { type: Boolean, default: false },
});

// 定义emits
const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "save", rule: any): void;
}>();

// 表单引用
const ruleFormRef = ref<InstanceType<typeof ElForm>>();

// 表单数据
const ruleForm = reactive({
  id: "",
  name: "",
  type: "ip",
  description: "",
  condition: {
    ip: "",
    ipRange: "",
    port: "",
    scene: "",
    vulnKeyword: "",
    matchType: "exact",
  },
  applicableScenes: [] as string[],
  hasExpireTime: false,
  startTime: "",
  endTime: "",
  status: "启用中",
});

// 表单规则
const formRules = reactive({
  name: [{ required: true, message: "请输入规则名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择规则类型", trigger: "change" }],
});

// 监听visible变化
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      if (props.isEdit && props.rule) {
        // 编辑模式：填充表单
        const rule = props.rule;
        ruleForm.id = rule.id;
        ruleForm.name = rule.rule_name || rule.name || "";
        ruleForm.type = rule.rule_type || rule.type || "ip";
        ruleForm.description = rule.rule_description || rule.description || "";

        // 处理状态
        ruleForm.status = rule.is_enabled ? "启用中" : "已禁用";

        // 处理 match_condition
        const matchCondition = rule.match_condition;
        if (typeof matchCondition === "string") {
          // 字符串类型
          if (ruleForm.type === "ip") {
            ruleForm.condition.ip = matchCondition;
          } else if (ruleForm.type === "ip_range") {
            ruleForm.condition.ipRange = matchCondition;
          } else if (ruleForm.type === "port") {
            ruleForm.condition.port = matchCondition;
          } else if (ruleForm.type === "ip_port") {
            const parts = matchCondition.split(":");
            ruleForm.condition.ip = parts[0] || "";
            ruleForm.condition.port = parts[1] || "";
          } else if (ruleForm.type === "scene") {
            ruleForm.condition.scene = matchCondition;
          } else if (ruleForm.type === "vuln_type") {
            ruleForm.condition.vulnKeyword = matchCondition;
          }
        } else if (
          typeof matchCondition === "object" &&
          matchCondition !== null
        ) {
          // 对象类型，提取 value
          if (matchCondition.value) {
            if (ruleForm.type === "ip") {
              ruleForm.condition.ip = matchCondition.value;
            } else if (ruleForm.type === "ip_range") {
              ruleForm.condition.ipRange = matchCondition.value;
            } else if (ruleForm.type === "port") {
              ruleForm.condition.port = matchCondition.value;
            } else if (ruleForm.type === "scene") {
              ruleForm.condition.scene = matchCondition.value;
            } else if (ruleForm.type === "vuln_type") {
              ruleForm.condition.vulnKeyword = matchCondition.value;
            }
          }
        }

        // 处理适用维度
        if (rule.applicable_dimensions) {
          const dimensions = rule.applicable_dimensions.split(",");
          const sceneMap: Record<string, string> = {
            unreported_asset: "unreported",
            high_risk_asset: "high_risk",
            vuln_scan: "vuln_scan",
            intel_hit: "intel_hit",
            reviewed: "reviewed",
          };
          ruleForm.applicableScenes = dimensions
            .map((d: string) => sceneMap[d.trim()] || d.trim())
            .filter((s: string) => s);
        }

        // 处理生效时间
        if (rule.effective_start || rule.effective_end) {
          ruleForm.hasExpireTime = true;
          ruleForm.startTime = rule.effective_start || "";
          ruleForm.endTime = rule.effective_end || "";
        } else {
          ruleForm.hasExpireTime = false;
          ruleForm.startTime = "";
          ruleForm.endTime = "";
        }
      } else {
        // 新增模式：重置表单
        ruleForm.id = "";
        ruleForm.name = "";
        ruleForm.type = "ip";
        ruleForm.description = "";
        ruleForm.condition = {
          ip: "",
          ipRange: "",
          port: "",
          scene: "",
          vulnKeyword: "",
          matchType: "exact",
        };
        ruleForm.applicableScenes = [];
        ruleForm.hasExpireTime = false;
        ruleForm.startTime = "";
        ruleForm.endTime = "";
        ruleForm.status = "启用中";
      }
    } else {
      // 关闭弹窗时重置表单
      ruleFormRef.value?.resetFields();
    }
  },
  { immediate: true }
);

// 规则类型变化处理
const handleTypeChange = (type: string) => {
  // 清空其他类型的条件
  Object.keys(ruleForm.condition).forEach((key) => {
    ruleForm.condition[key as keyof typeof ruleForm.condition] = "";
  });
};

// 全选场景处理
const handleAllSceneChange = (checked: boolean) => {
  if (checked) {
    ruleForm.applicableScenes = [
      "unreported",
      "high_risk",
      "vuln_scan",
      "intel_hit",
      "reviewed",
      "all",
    ];
  } else {
    ruleForm.applicableScenes = [];
  }
};

// 保存
const handleSave = async () => {
  const valid = await ruleFormRef.value?.validate();
  if (!valid) return;

  // 验证匹配条件
  let hasCondition = false;
  if (ruleForm.type === "ip" && ruleForm.condition.ip) {
    hasCondition = true;
  } else if (ruleForm.type === "ip_range" && ruleForm.condition.ipRange) {
    hasCondition = true;
  } else if (ruleForm.type === "port" && ruleForm.condition.port) {
    hasCondition = true;
  } else if (
    ruleForm.type === "ip_port" &&
    ruleForm.condition.ip &&
    ruleForm.condition.port
  ) {
    hasCondition = true;
  } else if (ruleForm.type === "scene" && ruleForm.condition.scene) {
    hasCondition = true;
  } else if (ruleForm.type === "vuln_type" && ruleForm.condition.vulnKeyword) {
    hasCondition = true;
  }

  if (!hasCondition) {
    ElMessage.warning("请填写匹配条件");
    return;
  }

  // 构建提交数据（直接传递表单数据，由父组件处理转换）
  emit("save", { ...ruleForm });
};

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};
</script>

<style scoped lang="scss">
.rule-form {
  padding: 10px 0;

  .form-hint {
    color: #999;
    font-size: 12px;
    margin-top: 5px;
  }

  .condition-group {
    .condition-input {
      width: 100%;
      margin-bottom: 5px;
    }

    .radio-group {
      margin-top: 10px;
      display: flex;
      gap: 20px;
    }
  }

  .expire-checkbox {
    margin-bottom: 10px;
  }

  .time-picker {
    width: 100%;
  }

  .el-checkbox {
    margin-right: 15px;
    margin-bottom: 10px;
  }
}
</style>
